package com.mjk.common.tools.encrypt;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.util.Base64;


@SuppressWarnings("restriction")
public class DesUtil {
	private DesUtil() {}

	private static final String ALGORITHM = "DES";

	public static String encrypt(String data, String key) {
		try {
			byte[] bt = encrypt(data.getBytes(), key.getBytes());
			return Base64.getEncoder().encodeToString(bt);
		} catch (Exception e) {
			e.printStackTrace(); // 使用日志记录异常
		}
		return "";
	}

	public static String decrypt(String data, String key) {
		if (data == null) return null;
		byte[] bt = decrypt(Base64.getDecoder().decode(data), key.getBytes());
		return new String(bt);
	}

	private static byte[] encrypt(byte[] data, byte[] key) {
		try {
			DESKeySpec dks = new DESKeySpec(key);
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
			SecretKey securekey = keyFactory.generateSecret(dks);
			Cipher cipher = Cipher.getInstance(ALGORITHM);
			cipher.init(Cipher.ENCRYPT_MODE, securekey);
			return cipher.doFinal(data);
		} catch (Exception e) {
			e.printStackTrace(); // 使用日志记录异常
		}
		return new byte[0];
	}

	private static byte[] decrypt(byte[] data, byte[] key) {
		try {
			DESKeySpec dks = new DESKeySpec(key);
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
			SecretKey securekey = keyFactory.generateSecret(dks);
			Cipher cipher = Cipher.getInstance(ALGORITHM);
			cipher.init(Cipher.DECRYPT_MODE, securekey);
			return cipher.doFinal(data);
		} catch (Exception e) {
			e.printStackTrace(); // 使用日志记录异常
		}
		return new byte[0];
	}
}